import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hockey/extensions/jzx_widget_extension.dart';
import 'package:hockey/jzx_apps.dart';
import 'package:hockey/models/jzx_media_data.dart';
import 'package:hockey/pages/jzx_post_detail/jzx_post_detail.dart';
import 'package:hockey/pages/jzx_user_homepage/jzx_user_homepage.dart';
import 'package:hockey/services/jzx_user.dart';
import 'package:hockey/widgets/common/jzx_network_image_view.dart';

import 'controller.dart';

class JzxPostsView extends GetView<JzxPostsController> {
  const JzxPostsView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      extendBodyBehindAppBar: true,
      // appBar: const JzxAAppBar(title: 'HomeView', isRootNavigator: true),
      body: Column(
        children: [
          SizedBox(height: kStatusBarHeight),
          Row(
            children: [
              Text(
                'Stick',
                style:
                    GoogleFonts.secularOne(fontSize: 36.w, color: Colors.white),
              ),
              Text(
                'Flow',
                style: GoogleFonts.secularOne(
                    fontSize: 36.w, color: const Color(0xFF63FF6A)),
              ),
              JzxGaps.expand,
              Obx(
                () => JzxNetworkAssets(
                  JzxUserService.to.avatar,
                  width: 36.w,
                  radius: 100,
                ),
              ),
            ],
          ).paddingSymmetric(horizontal: 20),
          const _PostView(),
          Expanded(
            child: Obx(
              () => MasonryGridView.count(
                mainAxisSpacing: 16,
                crossAxisSpacing: 11,
                padding: EdgeInsets.only(
                  left: 20,
                  right: 20,
                  top: 20,
                  bottom: Get.bottomBarHeight + 20,
                ),
                crossAxisCount: 2,
                itemCount: controller.items.length,
                itemBuilder: (context, index) {
                  final item = controller.items[index];
                  return JzxPostItemView(
                    item: item,
                    index: index,
                    height: index == 1 ? 184.w : 200.w,
                    onLike: () {
                      controller.likeOrCancel(item, index);
                    },
                  );
                },
              ),
            ),
          ),
        ],
      ).backgroud(Assets.images.normalBgv),
    );
  }
}

class JzxPostItemView extends StatelessWidget {
  const JzxPostItemView({
    super.key,
    required this.item,
    required this.index,
    this.canPushUser = true,
    this.height,
    this.onLike,
  });

  final JzxMediaData item;
  final int index;
  final bool canPushUser;
  final double? height;
  final VoidCallback? onLike;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        // Get.toNamed(kRouteJzxUserHomepage, parameters: {
        //   'author': item.author,
        //   'uid': item.user.userId,
        // });

        Get.toNamed(kRouteJzxPostDetail, arguments: item);
      },
      child: Container(
        height: height,
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
          // image: DecorationImage(
          //   image: AssetImage('assets/post/${item.cover}.jpg'),
          //   fit: BoxFit.cover,
          // ),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Positioned.fill(
              child: item.author == JzxUserService.to.author
                  ? Image.file(File(item.cover), fit: BoxFit.cover)
                  : Image.asset('assets/post/${item.cover}.jpg',
                      fit: BoxFit.cover),
            ),
            _ItemTitle(item: item, canPushUser: canPushUser),
            _ItemLiked(item: item, onTap: onLike),
          ],
        ),
      ),
    );
  }
}

class _PostView extends GetView<JzxPostsController> {
  const _PostView({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      // height: 88.w,
      constraints: BoxConstraints(
        minHeight: 88.w,
      ),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
      margin: const EdgeInsets.only(left: 20, right: 20, top: 25, bottom: 5),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          gradient: const LinearGradient(colors: [
            Color(0x663FE1D8),
            Color(0x6663FF6A),
          ])),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Container(
                  height: 40.w,
                  alignment: Alignment.topLeft,
                  child: CupertinoTextField(
                    controller: controller.content,
                    placeholder: 'Say something……',
                    maxLength: 500,
                    placeholderStyle: const TextStyle(color: Color(0x80FFFFFF)),
                    padding: EdgeInsets.zero,
                    maxLines: null,
                    decoration: const BoxDecoration(color: Colors.transparent),
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              JzxGaps.w5,
              Obx(
                () => Text.rich(
                  TextSpan(children: [
                    TextSpan(
                        text: '${controller.contentlength.value}',
                        style: myAppColors.white.font_16.medium),
                    TextSpan(
                        text: '/500', style: myAppColors.white.font_12.medium),
                  ]),
                ),
              ),
            ],
          ),
          JzxGaps.h10,
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWell(
                onTap: () {
                  controller.pickOthersInfo();
                },
                child: Assets.images.icImage.image(width: 17.w),
              ),
              InkWell(
                onTap: () {
                  controller.submitPost();
                },
                child: Assets.images.icPost.image(height: 24.w),
              ),
            ],
          )
        ],
      ),
    );
  }
}

class _ItemLiked extends GetView<JzxPostsController> {
  const _ItemLiked({
    super.key,
    required this.item,
    this.onTap,
  });

  final JzxMediaData item;
  final VoidCallback? onTap;

  @override
  Widget build(BuildContext context) {
    return Positioned(
        top: 2,
        right: 2,
        child: InkWell(
          onTap: onTap,
          child: JzxBlurView(
            blur: 4,
            backgroundColor: const Color(0x40000000),
            padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.w),
            radius: 100,
            child: Row(
              children: [
                item.isLiked
                    ? Assets.images.icListLiked.image(width: 13.w)
                    : Assets.images.icListUnlike.image(width: 13.w),
                JzxGaps.w4,
                Text(
                  item.like.format,
                  style: myAppColors.white.font_12,
                ),
              ],
            ),
          ),
        ));
  }
}

class _ItemTitle extends StatelessWidget {
  const _ItemTitle({
    super.key,
    required this.item,
    this.canPushUser = true,
  });

  final JzxMediaData item;
  final bool canPushUser;

  @override
  Widget build(BuildContext context) {
    return JzxBlurView(
      blur: 4,
      backgroundColor: const Color(0x40000000),
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 3.w),
      borderRadius: const BorderRadius.only(
        bottomLeft: Radius.circular(12),
        bottomRight: Radius.circular(12),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          InkWell(
            onTap: () {
              if (canPushUser) {
                Get.toNamed(kRouteJzxUserHomepage, parameters: {
                  'uid': item.user.userId,
                  'author': item.author,
                });
              }
            },
            child: JzxUserFrame(
              item.user.avatar,
              30.w,
              level: item.user.level,
            ),
          ),
          JzxGaps.w4,
          Expanded(
            child: Text(
              item.title,
              style: myAppColors.white.font_10,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }
}
